<template>
  <div class='map-contaienr'>
    <div class="mapDiv" ref="map" style="width: 100%; height: 466px"></div>
    <div class="map-Contern">
      <el-form class="map-form" size="small" ref="mapForm" :model="mapForm" label-width="0">
        <el-form-item label="">
          <el-input v-model="mapForm.mapSearch" placeholder="搜索地区">
            <template slot="suffix">
              <i class="el-icon-search" @click="mapSearchFn"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <span style="color: #8fabbf">经纬度</span>
          <el-input v-model="mapForm.maplnglat" placeholder=""> </el-input>
        </el-form-item>
        <el-form-item label="">
          <span style="color: #8fabbf">地址</span>
          <el-input v-model="mapForm.mapaddress" placeholder="请选择地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="map-footer-btn">
        <el-button @click="Lowercancel()" class="btn_cancel">取 消</el-button>
        <el-button type="primary" @click="mapSubmitForm" class="btn_primary">确 定</el-button>
      </div>
    </div>
  </div>
</template>

<script>

import Map from "ol/Map";
import View from "ol/View";
// import OSM from 'ol/source/OSM';
import XYZ from "ol/source/XYZ";
// import TileLayer from 'ol/layer/Tile';
// 点位引用
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import { Circle, Fill, Icon, Stroke, Style, Text } from "ol/style.js";
import { OGCMapTile, Vector as VectorSource } from "ol/source.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
export default {
  props: {

  },
  data () {
    return {
      // 地图表单
      mapForm: {
        mapSearch: undefined,
        maplnglat: undefined,
        mapaddress: undefined,
      },
      isdisabled: true,
      // 父组件传递过来的值
      rowinfo: this.rowData,
      // 项目类型名称
      TypeNameList: this.projectPointTypeList,

      // 地图
      map: null,
      // 是否可见地图
      isVisibleMap: false,
      // 天地图token
      mapToken: "f01023d9e7977aa8946e0137daf05a2b",
      // 地图矢量图层源
      vectorSource: undefined,
      // 地图点位图片样式
      iconStyle: undefined,
    };
  },
  computed: {},
  watch: {},
  methods: {
    // 地图初始化
    initMap () {
      this.$nextTick(() => {
        // 创建一个矢量要素
        const iconFeature = new Feature({
          geometry: new Point([118.1163, 24.4673]),
        });
        // 定义图片样式
        this.iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 1],
            src: "https://openlayers.org/en/latest/examples/data/icon.png",
          }),
        });
        // 设置要素样式
        iconFeature.setStyle(this.iconStyle);

        // 创建矢量数据源和图层
        this.vectorSource = new VectorSource({
          features: [iconFeature],
        });
        const vectorLayer = new VectorLayer({
          source: this.vectorSource,
        });
        this.map = new Map({
          layers: [
            new TileLayer({
              source: new XYZ({
                url: `http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
              }),
              // setStyle: "black",
            }),
            new TileLayer({
              source: new XYZ({
                url: `http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
              }),
              // setStyle: "black",
            }),
            vectorLayer,
          ],
          view: new View({
            center: [118.1163, 24.4673],
            zoom: 12,
            projection: "EPSG:4326",
          }),
          // 使用 Vue 的 ref 来引用 DOM 元素
          target: this.$refs.map,
        });
        this.map.addEventListener("click", this.MapClick);
      });
    },
    // 地图点击事件
    MapClick (e) {
      let coordinate = e.coordinate;
      console.log(coordinate);
      this.getGeocoderAddress(coordinate[0], coordinate[1]).then((res) => {
        this.mapForm.mapaddress = res.result.formatted_address;
        console.log(res);
      });
      // 创建一个新的图标要素
      this.mapForm.maplnglat = coordinate.join("/");
      let newIconFeature = new Feature({
        geometry: new Point(coordinate),
      });
      newIconFeature.setStyle(this.iconStyle);
      // 清除之前的图标要素
      this.vectorSource.clear();
      // 添加新的图标要素
      this.vectorSource.addFeature(newIconFeature);
    },
    // 根据地图坐标获取具体地址
    getGeocoderAddress (lon, lat) {
      return request({
        url: `/geocoder?postStr={'lon':${lon},'lat':${lat},'ver':1}&type=geocode&tk=${this.mapToken}`,
        method: "post",
        type: "map",
      });
    },
    // 地图搜索功能
    mapSearchFn () {
      console.log(111);
      let keyWord = this.mapForm.mapSearch;
      this.getGeocoderLonLat(keyWord).then((res) => {
        let newIconFeature = new Feature({
          geometry: new Point([res.location.lon, res.location.lat]),
        });
        newIconFeature.setStyle(this.iconStyle);
        this.vectorSource.clear();
        console.log(res.location.lon, res.location.lat);
        this.map.getView().setCenter([res.location.lon, res.location.lat]);
        this.map.getView().setZoom(12);
        // 添加新的图标要素
        this.vectorSource.addFeature(newIconFeature);
        this.mapForm.maplnglat = res.location.lon + "," + res.location.lat;
      });
    },
    // 根据地址获取对应的地图坐标
    getGeocoderLonLat (keyWord) {
      return request({
        url: `/geocoder?ds={'keyWord':"${keyWord}"}&tk=${this.mapToken}`,
        method: "post",
        type: "map",
      });
    },
    // 地图确定按钮
    mapSubmitForm () {
      let tempLonLatArr = this.mapForm.maplnglat;
      this.formModel.lng = tempLonLatArr.split("/")[0];
      this.formModel.lat = tempLonLatArr.split("/")[1];
      this.isVisibleMap = false;
    },
  },
  components: {},
}
</script>

<style lang='less' scoped>
</style>